/*!
 * \file cicsts_comm.c
 *
 * \brief CICSTS模块共通文件
 *
 * All Rights Reserved Copyright (C) 2014 broada,Co.,Ltd.
 *
 * \version 1.0
 * \author songbb
 * \date 2016/04/22
 *
 */

#include <stdio.h>
#include <memory.h>
#include <sys/time.h>

#include "frmem.h"
#include "frlog.h"
#include "frreport_comm.h"
#include "frct_comm.h"
#include "frreport_comm.h"

#include "cicsts_core.h"
#include "cicsts_comm.h"

static char hex_asc[] = "0123456789abcdef";
#define hex_asc_lo(x)   hex_asc[((x) & 0x0f)]
#define hex_asc_hi(x)   hex_asc[((x) & 0xf0) >> 4]

void cicsts_free(void **pp_buffer)
{
    if (pp_buffer == NULL || *pp_buffer == NULL)
        return;

    frfree(*pp_buffer);
    *pp_buffer = NULL;
    return;
}

/*******************************************************************************
*  FUNC     :  时间格式化成 2015-03-29 22:25:12.448671 的格式
*  ARGS     :  *p_tv                           (时间戳)
*           :  *p_time                         (buffer)
*           :  ui_time_size                    (buffer size)
*  RTN      :
*  NOTE     :
*******************************************************************************/
FR_STATIC int __cicsts_frtime2datetimestr(struct timeval *p_tv
                                        , char *p_time
                                        , unsigned int ui_time_size)
{
    struct tm *p_tm = NULL;

    if(p_tv == NULL || p_time == NULL || ui_time_size <= 1)
        return FR_FAIL;

    p_tm = localtime(&(p_tv->tv_sec));

    snprintf(p_time,ui_time_size,"%04d-%02d-%02d %02d:%02d:%02d.%06ld",
             p_tm->tm_year + 1900,p_tm->tm_mon + 1,p_tm->tm_mday,
             p_tm->tm_hour,p_tm->tm_min,p_tm->tm_sec,p_tv->tv_usec);

    return FR_SUCC;
}

void cicsts_print_timeval(struct timeval st_timestamp)
{
    char arr_buff[64];
    __cicsts_frtime2datetimestr(&st_timestamp, arr_buff, sizeof(arr_buff));
    printf(":[%s]\n", arr_buff);
}

void cicsts_bin_to_hex_string(char *p_inbuff
                            , int i_len
                            , char *p_outbuff)
{
    int i_loop;
    char c;
    int i_used = 0;

    for (i_loop = 0; i_loop < i_len; i_loop++)
    {
        c = p_inbuff[i_loop];
        p_outbuff[i_used++] = hex_asc_hi(c);
        p_outbuff[i_used++] = hex_asc_lo(c);
    }

    return;
}

void cicsts_print_hex_string(char *p_buff
                        , int i_len)
{
    int i_loop;

    for (i_loop = 0; i_loop < i_len; i_loop++)
        printf("%02x", p_buff[i_loop] & 0xFF);

    return;
}

void cicsts_print_packet_specified(L7_cicsts_packet *p_st_cicsts_packet
                                , int i_pos
                                , int i_len)
{
    if (p_st_cicsts_packet == NULL)
        return;
    char *p_buff_tmp = NULL;
    if (bytebuff_show(p_st_cicsts_packet->p_st_packet, i_pos, i_len, &p_buff_tmp) != FR_SUCC)
        return;
    cicsts_print_hex_string(p_buff_tmp, i_len);
    cicsts_free((void **) &p_buff_tmp);
    return;
}

void cicsts_print_packet_current(L7_cicsts_packet *p_st_cicsts_packet)
{
    if (p_st_cicsts_packet == NULL)
        return;
    char *p_buff_tmp = NULL;
    if (bytebuff_show(p_st_cicsts_packet->p_st_packet, bytebuff_getPosition(p_st_cicsts_packet->p_st_packet), bytebuff_remaining(p_st_cicsts_packet->p_st_packet), &p_buff_tmp) != FR_SUCC)
        return;
    cicsts_print_hex_string(p_buff_tmp, bytebuff_remaining(p_st_cicsts_packet->p_st_packet));
    cicsts_free((void **) &p_buff_tmp);
    return;
}

void cicsts_print_packet(L7_cicsts_packet *p_st_cicsts_packet)
{
    if (p_st_cicsts_packet == NULL)
        return;
    char *p_buff_tmp = NULL;
    if (bytebuff_show(p_st_cicsts_packet->p_st_packet, 0, bytebuff_length(p_st_cicsts_packet->p_st_packet), &p_buff_tmp) != FR_SUCC)
        return;
    cicsts_print_hex_string(p_buff_tmp, bytebuff_length(p_st_cicsts_packet->p_st_packet));
    cicsts_free((void **) &p_buff_tmp);
    return;
}

int cicsts_packet_is_in_fragment(L7_cicsts_packet *p_st_cicsts_packet)
{
    if (p_st_cicsts_packet == NULL)
        return FR_NO;

    return (p_st_cicsts_packet->fragment_state == APM_CICSTS_FRAGMENT_NEED_NEXT_REQ_PACKET
            || p_st_cicsts_packet->fragment_state == APM_CICSTS_FRAGMENT_NEED_NEXT_RESP_PACKET) ? FR_YES : FR_NO;
}

void cicsts_free_stmt(L7_cicsts_stmt **pp_st_stmt)
{
    if (pp_st_stmt == NULL || *pp_st_stmt == NULL)
        return;

    frreport_body_l7list_free(&((*pp_st_stmt)->p_report_comm));
    frreport_body_l7list_free(&((*pp_st_stmt)->p_report_req));

    cicsts_free((void **) pp_st_stmt);

    return;
}

void cicsts_stmt_node_free(Frlist_node *p_st_node)
{
    if (p_st_node == NULL || p_st_node->data == NULL)
        return;

    L7_cicsts_stmt *p_st_stmt = (L7_cicsts_stmt *) FRLIST_GET_NODE_DATA(p_st_node);
    cicsts_free_stmt(&p_st_stmt);
    p_st_node->data = NULL;

    frlist_node_data_free(p_st_node);
}

int cicsts_report_msg_data_req(Conntrack *p_st_conn
                            , L7_cicsts_packet *p_st_cicsts_packet
                            , Frreport_body_data *p_st_body
                            , Frhash_header *p_st_hash_report
                            , L7_cicsts_stmt *p_st_stmt)
{
    CICSTS_PRINT_INFO("cicsts_report_msg_data_req\n");

    L7_session *p_st_session = frct_get_session(p_st_conn);
    Frreport_data *p_st_report_data = NULL;

    if (p_st_conn == NULL ||
        p_st_cicsts_packet == NULL ||
        p_st_body == NULL ||
        p_st_hash_report == NULL ||
        p_st_stmt == NULL)
        return FR_FAIL;

    if (frreport_body_l7_add_str(p_st_body, APM_REPORT_KEY_SESSION_ID, p_st_session->arr_session_id) != FR_SUCC)
        goto error;
    if (frreport_body_l7_add_connInfo(p_st_body, p_st_conn) != FR_SUCC)
        goto error;
    if (frreport_body_l7_add_ulong(p_st_body, APM_REPORT_KEY_REQ_ID, frct_seq_increase(p_st_conn)) != FR_SUCC)
        goto error;
    if (frreport_body_l7_add_int(p_st_body, APM_REPORT_KEY_REQ_ISRESPREQUIRED, FR_YES) != FR_SUCC)
        goto error;
    if (frreport_body_l7_add_timeval(p_st_body, APM_REPORT_KEY_REQ_START_TIMESTAMP, &(p_st_cicsts_packet->st_timestamp_first)) != FR_SUCC)
        goto error;
    if (frreport_body_l7_add_timeval(p_st_body, APM_REPORT_KEY_REQ_END_TIMESTAMP, &(p_st_cicsts_packet->st_timestamp_last)) != FR_SUCC)
        goto error;
    if (frreport_body_l7_add_long(p_st_body, APM_REPORT_KEY_REQ_SEND_TIME_US, frtime_diff(&(p_st_cicsts_packet->st_timestamp_first), &(p_st_cicsts_packet->st_timestamp_last))) != FR_SUCC)
        goto error;
    if (frreport_body_l7_add_ulong(p_st_body, APM_REPORT_KEY_REQ_DATA_BYTES, p_st_cicsts_packet->ui_length) != FR_SUCC)
        goto error;

    frreport_body_l7list_free(&(p_st_stmt->p_report_comm));
    p_st_stmt->p_report_comm = FRREPORT_BODY_L7LIST_CLONE_COMM(p_st_body);

    frreport_body_l7list_free(&(p_st_stmt->p_report_req));
    p_st_stmt->p_report_req = FRREPORT_BODY_L7LIST_CLONE_REQ(p_st_body);

    if ((p_st_report_data = frreport_data_l7_new(FRREPORT_TYPE_L7DATA_REQ)) == NULL)
        goto error;

    if (frreport_data_add_body(p_st_report_data, p_st_body) != FR_SUCC)
        goto error;

    if (frreport_data_hash(p_st_hash_report, p_st_report_data) != FR_SUCC)
        goto error;

    p_st_stmt->st_req_end_timestamp.tv_sec = p_st_cicsts_packet->st_timestamp_last.tv_sec;
    p_st_stmt->st_req_end_timestamp.tv_usec = p_st_cicsts_packet->st_timestamp_last.tv_usec;

    return FR_SUCC;
error:
    frreport_data_free(&p_st_report_data);
    return FR_FAIL;
}

int cicsts_report_msg_data_resp(Conntrack *p_st_conn
                                , L7_cicsts_packet *p_st_cicsts_packet
                                , Frreport_body_data *p_st_body
                                , Frhash_header *p_st_hash_report)
{
    CICSTS_PRINT_INFO("cicsts_report_msg_data_resp\n");

    L7_session *p_st_session = frct_get_session(p_st_conn);
    L7session_cicsts_private *p_st_session_private = (L7session_cicsts_private *) frct_get_session_private(p_st_session);
    Frhash_header *p_hash_stmt = p_st_session_private->p_hash_stmt;
    L7_cicsts_stmt *p_st_stmt = NULL;
    Frlist_node *p_st_node = NULL;
    Frreport_data *p_st_report_data = NULL;

    if ((p_st_node = frhash2_getLong(p_hash_stmt, p_st_cicsts_packet->ui_msg_id)) == NULL)
        goto error;
    if ((p_st_stmt = (L7_cicsts_stmt *) FRLIST_GET_NODE_DATA(p_st_node)) == NULL)
        goto error;

    if (p_st_stmt->p_report_comm == NULL || p_st_stmt->p_report_req == NULL)
    {
        CICSTS_PRINT_EMERG("Has no request data, do not report response\n");
        CICSTS_FRLOG_ERROR("Has no request data, do not report response");
        return FR_FAIL;
    }

    if (FRREPORT_BODY_L7LIST_SET_COMM(p_st_body, &(p_st_stmt->p_report_comm)) != FR_SUCC)
        goto error;
    if (FRREPORT_BODY_L7LIST_SET_REQ(p_st_body, &(p_st_stmt->p_report_req)) != FR_SUCC)
        goto error;

    if (p_st_stmt->st_resp_start_timestamp.tv_sec != 0 || p_st_stmt->st_resp_start_timestamp.tv_usec != 0)
    {
        if (frreport_body_l7_add_timeval(p_st_body, APM_REPORT_KEY_RESP_START_TIMESTAMP, &(p_st_stmt->st_resp_start_timestamp)) != FR_SUCC)
            goto error;
    }
    else
    {
        if (frreport_body_l7_add_timeval(p_st_body, APM_REPORT_KEY_RESP_START_TIMESTAMP, &(p_st_cicsts_packet->st_timestamp_first)) != FR_SUCC)
            goto error;
    }
    if (frreport_body_l7_add_timeval(p_st_body, APM_REPORT_KEY_RESP_END_TIMESTAMP, &(p_st_cicsts_packet->st_timestamp_last)) != FR_SUCC)
        goto error;
    if (p_st_stmt->ul_resp_server_time_us != 0L)
    {
        if (frreport_body_l7_add_long(p_st_body, APM_REPORT_KEY_RESP_SERVER_TIME_US, p_st_stmt->ul_resp_server_time_us) != FR_SUCC)
            goto error;
    }
    else if (p_st_stmt->st_resp_start_timestamp.tv_sec != 0 || p_st_stmt->st_resp_start_timestamp.tv_usec != 0)
    {
        if (frreport_body_l7_add_long(p_st_body, APM_REPORT_KEY_RESP_SERVER_TIME_US, frtime_diff(&(p_st_stmt->st_req_end_timestamp), &(p_st_stmt->st_resp_start_timestamp))) != FR_SUCC)
            goto error;
    }
    else
    {
        if (frreport_body_l7_add_long(p_st_body, APM_REPORT_KEY_RESP_SERVER_TIME_US, frtime_diff(&(p_st_stmt->st_req_end_timestamp), &(p_st_cicsts_packet->st_timestamp_first))) != FR_SUCC)
            goto error;
    }
    if (p_st_stmt->st_resp_start_timestamp.tv_sec != 0 || p_st_stmt->st_resp_start_timestamp.tv_usec != 0)
    {
        if (frreport_body_l7_add_long(p_st_body, APM_REPORT_KEY_RESP_DOWNLOAD_TIME_US, frtime_diff(&(p_st_stmt->st_resp_start_timestamp), &(p_st_cicsts_packet->st_timestamp_last))) != FR_SUCC)
            goto error;
    }
    else
    {
        if (frreport_body_l7_add_long(p_st_body, APM_REPORT_KEY_RESP_DOWNLOAD_TIME_US, frtime_diff(&(p_st_cicsts_packet->st_timestamp_first), &(p_st_cicsts_packet->st_timestamp_last))) != FR_SUCC)
            goto error;
    }
    if (frreport_body_l7_add_ulong(p_st_body, APM_REPORT_KEY_RESP_DATA_BYTES, p_st_cicsts_packet->ui_length) != FR_SUCC)
        goto error;

    if ((p_st_report_data = frreport_data_l7_new(FRREPORT_TYPE_L7DATA_RESP)) == NULL)
        goto error;

    if (frreport_data_add_body(p_st_report_data, p_st_body) != FR_SUCC)
        goto error;

    if (frreport_data_hash(p_st_hash_report, p_st_report_data) != FR_SUCC)
        goto error;

    return FR_SUCC;
error:
    frreport_data_free(&p_st_report_data);
    return FR_FAIL;
}
